////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//  Filename:    DerbyDollarsGuts.cpp                                         //
//  Developer:   Tommy Riddle                                                 //
//  Create date: 03/18/2005                                                   //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//  Description: This is the class implementation for the slot gut of the     //
//               Australian Slot machine called Derby Dollars.                //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
//        Copyright (c) 2005 - Realtime Gaming.  All rights reserved.         //
////////////////////////////////////////////////////////////////////////////////

#include "DerbyDollarsGuts.h"

////////////////////////////////////////////////////////////////////////////
/// DerbyDollarsGuts::m_aLineWinSpinResults
///
/// This array is used to quickly get the SpinResult for the number of
/// icons.  It is indexed by wheel icon and then count.  So to get the
/// SpinResult for 5 Ladies, use the following code snippet:
///
///		SpinResult result = m_aLineWinSpinResults[ ICON_LADY ][ 5 ];
///
/// In this example result would be set to EVT_FIVE_LADY.
////////////////////////////////////////////////////////////////////////////
DerbyDollarsGuts::SpinResult DerbyDollarsGuts::m_aLineWinSpinResults[][6] = 
{
// Number of icons:			0			1				2					3						4						5
/* ICON_NINE */			{	EVT_LOSER,	EVT_LOSER,		EVT_LOSER,			EVT_THREE_NINE,			EVT_FOUR_NINE,			EVT_FIVE_NINE		},
/* ICON_TEN */			{	EVT_LOSER,	EVT_LOSER,		EVT_LOSER,			EVT_THREE_TEN,			EVT_FOUR_TEN,			EVT_FIVE_TEN		},
/* ICON_JACK */			{	EVT_LOSER,	EVT_LOSER,		EVT_LOSER,			EVT_THREE_JACK,			EVT_FOUR_JACK,			EVT_FIVE_JACK		},
/* ICON_QUEEN */		{	EVT_LOSER,	EVT_LOSER,		EVT_LOSER,			EVT_THREE_QUEEN,		EVT_FOUR_QUEEN,			EVT_FIVE_QUEEN		},
/* ICON_KING */			{	EVT_LOSER,	EVT_LOSER,		EVT_TWO_KING,		EVT_THREE_KING,			EVT_FOUR_KING,			EVT_FIVE_KING		},
/* ICON_ACE */			{	EVT_LOSER,	EVT_LOSER,		EVT_TWO_ACE,		EVT_THREE_ACE,			EVT_FOUR_ACE,			EVT_FIVE_ACE		},
/* ICON_BINOCULARS */	{	EVT_LOSER,	EVT_LOSER,		EVT_TWO_BINOCULARS,	EVT_THREE_BINOCULARS,	EVT_FOUR_BINOCULARS,	EVT_FIVE_BINOCULARS	},
/* ICON_TROPHY */		{	EVT_LOSER,	EVT_LOSER,		EVT_TWO_TROPHY,		EVT_THREE_TROPHY,		EVT_FOUR_TROPHY,		EVT_FIVE_TROPHY		},
/* ICON_JOCKEY */		{	EVT_LOSER,	EVT_LOSER,		EVT_TWO_JOCKEY,		EVT_THREE_JOCKEY,		EVT_FOUR_JOCKEY,		EVT_FIVE_JOCKEY		},
/* ICON_LADY */			{	EVT_LOSER,	EVT_LOSER,		EVT_TWO_LADY,		EVT_THREE_LADY,			EVT_FOUR_LADY,			EVT_FIVE_LADY		},
/* ICON_COIN */			{	EVT_LOSER,	EVT_LOSER,		EVT_LOSER,			EVT_LOSER,				EVT_LOSER,				EVT_LOSER			},
/* ICON_HORSE */		{	EVT_LOSER,	EVT_ONE_HORSE,	EVT_TWO_HORSE,		EVT_THREE_HORSE,		EVT_FOUR_HORSE,			EVT_FIVE_HORSE		}
};

////////////////////////////////////////////////////////////////////////////
/// DerbyDollarsGuts::m_aScatterWinSpinResults
///
/// This array is used to quickly get the SpinResult for the number of
/// icons.  It is indexed by icon count only, since Coins are the only
/// scatter win.  So to get the SpinResult for 5 Coins, use the
/// following code snippet:
///
///		SpinResult result = m_aScatterWinSpinResults[ 5 ];
///
/// In this example result would be set to EVT_FIVE_COIN.
////////////////////////////////////////////////////////////////////////////
DerbyDollarsGuts::SpinResult DerbyDollarsGuts::m_aScatterWinSpinResults[6] = 
{
	// ICON_COIN			   Number of Icons
	EVT_LOSER,				// 0
	EVT_FEATURE_NEAR_MISS,	// 1
	EVT_TWO_COIN,			// 2
	EVT_THREE_COIN,			// 3
	EVT_FOUR_COIN,			// 4
	EVT_FIVE_COIN			// 5
};

////////////////////////////////////////////////////////////////////////////
/// @fn 	 DerbyDollarsGuts::DerbyDollarsGuts()   
///
/// This is the default constructor for the class.
////////////////////////////////////////////////////////////////////////////
DerbyDollarsGuts::DerbyDollarsGuts()
{
	// If this doesn't compile it means that someone probably added
	// another icon type but did not update the
	// m_aLineWinSpinResults array. 
	C_ASSERT( countof( m_aLineWinSpinResults ) == NUM_VALID_ICONS );
}

////////////////////////////////////////////////////////////////////////////
/// @fn 	 DerbyDollarsGuts::~DerbyDollarsGuts()
///
/// Destructor for DerbyDollarsGuts. 
////////////////////////////////////////////////////////////////////////////
DerbyDollarsGuts::~DerbyDollarsGuts()
{
}

////////////////////////////////////////////////////////////////////////////
/// @fn 	 DerbyDollarsGuts::SpinResult DerbyDollarsGuts::getHorseLineWinResult( uint8* stops ) const
///
/// @param   stops			The array of stop positions for the line.
///
/// @return	 SpinResult		A payout from the SpinResult enumeration.
///
/// This helper method is used to calculate the Horse line win payout.
////////////////////////////////////////////////////////////////////////////
DerbyDollarsGuts::SpinResult DerbyDollarsGuts::getHorseLineWinResult( uint8* stops ) const
{
	// Count how many Horses we have at the beginning of the line.
	for ( uint8 i = 0; i < getReelCount(); i++ )
    {
		// If this icon is not a Horse...
		if ( getIcon( getGameModeId(), i, stops[i] )->iconid != ICON_HORSE )
		{
			// then we have our total.
			break;
		}
    }

	// Use the array to look up the spin result for i Horses.
	return lookupLineWinSpinResult( ICON_HORSE, i );
}

////////////////////////////////////////////////////////////////////////////
/// @fn 	 DerbyDollarsGuts::SpinResult DerbyDollarsGuts::getLineWinResultWithPossibleSubstitution( uint8* stops, uint8 testIcon, bool& bSubstitution ) const
///
/// @param   stops			The array of stop positions for the line.
/// @param   testIcon		The icon we are looking for, typically the first icon on the line.
/// @param   bSubstitution	An output parameter that is set if a subsitution is used.
///
/// @return	 SpinResult		A payout from the SpinResult enumeration.
///
/// This helper method is used to calculate the line win payout with a possible substitution.
////////////////////////////////////////////////////////////////////////////
DerbyDollarsGuts::SpinResult DerbyDollarsGuts::getLineWinResultWithPossibleSubstitution(
	uint8* stops, uint8 testIcon, bool& bSubstitution ) const
{
	// Initialize the out parameter
	bSubstitution = false;

	// Loop through the remaining reels until the streak is over
	for ( int i = 1; i < getReelCount(); i++ )
    {
		// See what this icon is.
		uint8 currentIcon = getIcon( getGameModeId(), i, stops[i] )->iconid;

		// If the current icon is a Horse...
		if ( currentIcon == ICON_HORSE )
		{
			// then use it as a substitution symbol and continue on.
			bSubstitution = true;
			continue;
		}
		// Otherwise if the test icon is a Horse...
		else if ( testIcon == ICON_HORSE )
		{
			// then we still have a substitution.  In this case the line
			// started out with a Horse.
			bSubstitution = true;

			// We have now found our first icon that is not a Horse.  All
			// of the rest of the icons will have to match this one now for the
			// streak to continue, so change our test icon.
			testIcon = currentIcon;
			continue;
		}

		// If the current icon is not the test icon...
        if ( currentIcon != testIcon )
        {
			// then the streak is over so break out of the loop
			break;
        }
    }

	// If we made it all the way through and the testIcon is still a horse...
	if ( testIcon == ICON_HORSE )
	{
		// then this must be a 5 horse win, so reset the substitution flag.
		bSubstitution = false;
	}

	// Use the array to look up the spin result for i testIcons.
	return lookupLineWinSpinResult( testIcon, i );
}

////////////////////////////////////////////////////////////////////////////
/// @fn 	 bool DerbyDollarsGuts::doesHorseLineWinPayMore( SpinResult srHorse, SpinResult srOther ) const
///
/// @param   srHorse		The spin result to calculate the Horse payout for.
/// @param   srOther		The spin result to calculate the other payout for.
///
/// @return	 bool			True if the Horse win is larger.
///
/// This helper method is used to see which payout is larger.
////////////////////////////////////////////////////////////////////////////
bool DerbyDollarsGuts::doesHorseLineWinPayMore( SpinResult srHorse,
	SpinResult srOther ) const
{
	// Lookup the payout for the Horse line win.
	long nHorseLineWinPayout = getPayout( srHorse )->payoutAmount;

	// Lookup the payout for the other line win.
	long nOtherLineWinPayout = getPayout( srOther )->payoutAmount;

	// Return true if the Horse payout is bigger.
    return ( nHorseLineWinPayout > nOtherLineWinPayout );
}

////////////////////////////////////////////////////////////////////////////
/// @fn 	 DerbyDollarsGuts::classifyStops()   
///
/// @param   stops      The array of stop positions for the line.
/// @param   bet        The value of the line bet.
/// @param   line       The index of the line.
///
/// This helper method is used to calculate the payout on a line.
////////////////////////////////////////////////////////////////////////////
void DerbyDollarsGuts::classifyStops( SpinLine* spinline, uint8* stops, uint8 bet, uint8 line,
	uint8& rtnresult, uint8& multiplier )
{
	// Track the Horse result separately since it might be changed to a substitution.
	SpinResult srHorseLineWinResult = getHorseLineWinResult( stops );

	// Now see what the payout is if we use any Horses we find as substitution symbols.
	// Start with the icon on the first reel.
	uint8 testIcon = getIcon( getGameModeId(), 0, stops[0] )->iconid;

	// Declare a local variable to track whether or not we found a substitution.
	bool bSubstitution = false;

	// See what the spin result is if we used any Horses as substitution symbols.
	SpinResult srResultWithPossibleSubstitution =
		getLineWinResultWithPossibleSubstitution( stops, testIcon, bSubstitution );

	// Use the larger payout between the regular Horse evaluation compared to
	// the evaluation with the possible substitution.
    if ( doesHorseLineWinPayMore( srHorseLineWinResult,
		srResultWithPossibleSubstitution ) )
	{
		// The Horses by themselves pay out more so use the Horse result.
		rtnresult = srHorseLineWinResult;
	}
	else
	{
		// Otherwise the result with the substitution (if any) paid more so use it.
		rtnresult = srResultWithPossibleSubstitution;

		// If we did actually have a substitution and a winning spin...
		if ( bSubstitution && srResultWithPossibleSubstitution != EVT_LOSER )
		{
			// then add a note.
			spinline->addNote( NOTE_HORSE_SUBSTITUTION );
		}
	}
}

////////////////////////////////////////////////////////////////////////////
/// @fn		DerbyDollarsGuts::tryForJackpot()
///
///	This function tries to win the jackpot and adds the scatter if we hit
/// the jackpot.
////////////////////////////////////////////////////////////////////////////
void DerbyDollarsGuts::tryForJackpot( SlotSpin* spin )
{
	// If we are in the first paid spin (NOT a bonus spin)...
	if ( getGameModeId() == MODE_NORMAL ) 
	{
		// then try for the Random Progressive Jackpot
		// If we hit the jackpot...
		if ( getRandomProgressiveJackpotResult( spin->getSpinLineCount() )  ||
             m_bForceRandomJackpot==true )
		{
			// then add a jackpot scatter to the spin.
			spin->addScatter( 0,
				getPayout( EVT_RANDOM_PROGRESSIVE_WINNER )->payoutAmount, 1,
				true, EVT_RANDOM_PROGRESSIVE_WINNER, 0 );
		}
    }
}

////////////////////////////////////////////////////////////////////////////
/// @fn 	 DerbyDollarsGuts::getScatterWinResult()   
///
/// @param   spin				The current spin object.
/// @param   scatterPositions	The bit mask for the scatters positions that we find.
///
/// @return	 SpinResult			A payout from the SpinResult enumeration.
///
/// This helper method is used to evaluate the spin for scatters.
////////////////////////////////////////////////////////////////////////////
DerbyDollarsGuts::SpinResult DerbyDollarsGuts::getScatterWinResult( SlotSpin* spin, int32& scatterPositions ) const
{
	// Declare a local variable to keep up with the icon count.
	uint8 numScatterIcons = 0;

	// Initialize the scatterPositions.
	scatterPositions = 0;

	// Loop through each reel.
  	for( int reel = 0; reel < getReelCount(); reel++ )
	{
		// The position bit for the current icon in case it needs to be stored in a mask.
		uint8 position = reel;

		// Keep up with whether or not we find an icon on this reel
		bool bFoundScatterIconOnReel = false;

		// Loop through each row in the wheel house.
		for( int row = 0; row < 3; row++ )
		{
			// Get the current stop.
			uint8 stop = relativeWheelPosition( getGameModeId(), reel,
				spin->getStops()[ reel ], row );

			// Get the icon for the current stop.
			uint8 currentIcon = getIcon( getGameModeId(), reel, stop )->iconid;
			
			// If the icon is the one we are looking for...
			if ( currentIcon == ICON_COIN )
			{
				// then increase the icon count
				numScatterIcons++;

				// Set the bit in the position mask for this stop.
				scatterPositions |= 1 << position;

				// We found a scatter icon.
				bFoundScatterIconOnReel = true;
			}

			// Move to the next bit in the position mask.
            position += 5;
		}

		// If we didn't find a scatter icon on the reel...
		if ( !bFoundScatterIconOnReel )
		{
			// then we are done since this game pays left to right for
			// scatters, instead of any.
			break;
		}
	}

	return lookupScatterWinSpinResult( numScatterIcons );
}

////////////////////////////////////////////////////////////////////////////
/// @fn 	 DerbyDollarsGuts::evaluateScatterWin()
///
/// This function determines if the current spin wins a scatter payment and
/// adds the scatter.
////////////////////////////////////////////////////////////////////////////
void DerbyDollarsGuts::evaluateScatterWin( SlotSpin* spin, SpinResult srScatterResult, int32 scatterPositions )
{
	// If we got the scatter win (or almost got it)
	if ( srScatterResult != EVT_LOSER )
	{
		// Initialize the multiplier.
		int32 multiplier = 1;

		// If we are in free spin mode...
		if ( getGameModeId() == MODE_FREE_SPIN )
		{
			// then use the free spin multiplier.
			multiplier = MULTIPLIER_FREE_SPIN;
		}

		// Get the base payout for the scatter.
		int32 nPayout = getPayout( srScatterResult )->payoutAmount;
		
		// Scatters payout based on the total bet, so factor in the number of bet lines.
		nPayout *= spin->getSpinLineCount();

		// Add the payout (with multiplier) to the total win for this spin.
		increaseTotalWin( nPayout * multiplier );
    
		// Add a scatter to the spin.
		SlotScatter* pScatter = spin->addScatter( scatterPositions,
			nPayout * getBetPerLine(), multiplier, false, srScatterResult, 0 );

		// If the free spin multiplier was used...
		if ( multiplier == MULTIPLIER_FREE_SPIN )
		{
			// then add the free spin note.
			pScatter->addNote( NOTE_FREE_SPIN );
		}
	}
}

////////////////////////////////////////////////////////////////////////////
/// @fn 	 DerbyDollarsGuts::evaluateFeatureTrigger()
///
/// This function determines if the current spin triggers the free game
///	feature and adds the scatter.
////////////////////////////////////////////////////////////////////////////
void DerbyDollarsGuts::evaluateFeatureTrigger( SlotSpin* spin, SpinResult srScatterResult, int32 scatterPositions )
{
	// We need a place to keep up with how many free spins to award.
	int32 nFreeSpins = 0;

	// Figure out how many free spins they get.
	if ( srScatterResult == EVT_TWO_COIN )
	{
		nFreeSpins = 5;
	}
	else if ( srScatterResult == EVT_THREE_COIN )
	{
		nFreeSpins = 10;
	}
	else if ( srScatterResult == EVT_FOUR_COIN )
	{
		nFreeSpins = 15;
	}
	else if ( srScatterResult == EVT_FIVE_COIN )
	{
		nFreeSpins = 25;
	}
	else
	{
		return;
	}

	// Change the game mode.
	setGameModeId( MODE_FREE_SPIN );

	// Add the free spins.
	incrementFreeSpins( nFreeSpins );

	// Add a scatter to the spin for the feature trigger.
	spin->addScatter( scatterPositions, 0, 0, false,
		EVT_FREE_GAME_FEATURE, nFreeSpins );
}

////////////////////////////////////////////////////////////////////////////
/// @fn 	 DerbyDollarsGuts::classifyScatters( SlotSpin* spin )
///
/// @param   spin       Pointer to the spin with stop data.
///
/// This is an override of the framework method.  
/// It determines if the current spin merits free spins or scatter payments.
////////////////////////////////////////////////////////////////////////////
void DerbyDollarsGuts::classifyScatters( SlotSpin* spin )
{	
	// Try for the Random Progressive Jackpot
	tryForJackpot( spin );

	// Declare a local variable to track the scatter positions.
	int32 nScatterPositions = 0;

	// See if there is a scatter.
	SpinResult srResult = getScatterWinResult( spin, nScatterPositions );

	// Add the scatter, if any.
	evaluateScatterWin( spin, srResult, nScatterPositions );

	// See if we triggered the free game feature.
	evaluateFeatureTrigger( spin, srResult, nScatterPositions );
}

////////////////////////////////////////////////////////////////////////////
/// @fn 	 DerbyDollarsGuts::isValidGuts()   
///
/// @return	 bool8      True if gut is valid.    
///
/// This helper method is used to see if the current gut ID is valid.
////////////////////////////////////////////////////////////////////////////
bool8 DerbyDollarsGuts::isValidGuts()
{
	// Make sure that the m_aLineWinSpinResults array has an entry for each reel,
	// and an additional entry in case there are 0 icons on the line.
	// Note:  we can't do this in the constructor because we have to call
	// getReelCount.
	ASSERT( countof( m_aLineWinSpinResults[0] ) == getReelCount( MODE_NORMAL ) + 1 );

	// Make sure that the m_aScatterWinSpinResults array has an entry for each reel,
	// and an additional entry in case there are 0 scatter icons.
	ASSERT( countof( m_aScatterWinSpinResults ) == getReelCount( MODE_NORMAL ) + 1 );

	// Now make sure that both game modes have the same number of reels.
	ASSERT( getReelCount( MODE_NORMAL ) == getReelCount( MODE_FREE_SPIN ) );

	// Finally just check to see if the gut is within the right range.
    return ( getGutsId() >= 1100 && getGutsId() < 1200 );
}

////////////////////////////////////////////////////////////////////////////
/// @fn 	 DerbyDollarsGuts::getGameModeMultiplierAndNoteId( uint8& nGameModeMultiplier, uint8& nNoteId )
///
/// @param   nGameModeMultiplier	The multiplier for the game mode.
/// @param   nNoteId				The note ID for the game mode.
///
/// This helper method is used to get the game mode multiplier and note ID.
////////////////////////////////////////////////////////////////////////////
void DerbyDollarsGuts::getGameModeMultiplierAndNoteId( uint8& nGameModeMultiplier,
	uint8& nNoteId )
{
	// If we are in free spin mode...
    if ( getGameModeId() == MODE_FREE_SPIN )
    {
		// then return the free spin multiplier...
        nGameModeMultiplier = MULTIPLIER_FREE_SPIN;

		// and the free spin note.
        nNoteId = NOTE_FREE_SPIN;
    }
	// Otherwise...
    else
    {
		// just defer to the base class.
        SlotGuts::getGameModeMultiplierAndNoteId( nGameModeMultiplier, nNoteId );
    }
}


////////////////////////////////////////////////////////////////////////////////////////////////////
//
//	Debugging code
//
////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////
/// @fn 	 DerbyDollarsGuts::preSpinClassifyResults( SlotSpin* spin )
///
/// @param   spin       Pointer to the spin with stop data.
///
/// This method is overridden in debug spins mode to alter the reel stops.
////////////////////////////////////////////////////////////////////////////
void DerbyDollarsGuts::preSpinClassifyResults( SlotSpin* spin )
{
	SlotGuts::preSpinClassifyResults(spin);
	return;
}

////////////////////////////////////////////////////////////////////////////
/// @fn 	 DerbyDollarsGuts::Debug_SetLoserStops( uint8* pStops )
///
/// @param   pStops		The stops to set.
///
/// Base class override, returns a losing spin triggered by the debug tool
////////////////////////////////////////////////////////////////////////////
void DerbyDollarsGuts::Debug_SetLoserStops( uint8* pStops )
{
	pStops[0]=0;
	pStops[1]=3;
	pStops[2]=0;
	pStops[3]=0;
	pStops[4]=0;
}